package com.newtribe.net;

import java.nio.* ;
import java.nio.channels.*  ;
import java.util.* ;
import java.net.InetSocketAddress;
import java.io.*;
/**
 * <p> </p>
 * <p>Description: Innovatation method</p>
 * <p>Copyright: Copyright (c)  newtribe innovation 2005</p>
 * <p> </p>
 * @author fuwei
 * @version 1.0
 */

public class NonBlockingServer {
	public NonBlockingServer() {
	}
	public static void main(String[] args) throws Exception {
		new NonBlockingServer().start() ;
	}
	Selector selector = null ;//the null blocking Selector ;
	public void start() throws Exception {
		selector = Selector.open() ;
		//register ServerSocketChannel .
		ServerSocketChannel serverChannel = ServerSocketChannel.open();
		serverChannel.socket().bind(new InetSocketAddress(8911));
		serverChannel.configureBlocking(false);
		serverChannel.register(selector, SelectionKey.OP_ACCEPT);

		while(true ) {

			System.out.println("...............................server is starting .....") ;
			int n =selector.select();
			if (n ==0)
				continue ;
			
			Iterator it = selector.selectedKeys().iterator();
			while (it.hasNext()) {
				SelectionKey key = (SelectionKey) it.next();
				it.remove();

				if (key.isAcceptable()) {


					System.out.println(key + "is acceptable ***********");
					ServerSocketChannel server = (ServerSocketChannel) key.channel();

					SocketChannel channel = server.accept();
					channel.configureBlocking(false);
					SelectionKey readKey = channel.register(selector,
							SelectionKey.OP_READ);


				}
				else if (key.isReadable()) {

					try {
						//read data from socket channel .
						System.out.println(key + "is readable ............") ;
						ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
						int count = ( (SocketChannel) key.channel()).read(
								byteBuffer);
						if (count > 0) {
							byteBuffer.flip();
							byte[] data = new byte[count];
							byteBuffer.get(data, 0, count);
							System.out.println(new String(data));
							//  key.channel().close();

						}
						else if (count < 0) {
							key.channel().close();
						}
						byteBuffer.clear();

					}
					catch (IOException ex) {

						ex.printStackTrace();
            			key.channel().close();

					}



				}


			}




		}


	}

}